package com.witmore.skyline.web.service.third.neutronAI;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jk.common.response.ResponseResult;
import com.jk.neutronai.NeutronAIApiClient;
import com.jk.neutronai.dto.ApiChatCompletionRequest;
import com.jk.neutronai.dto.ApiMessagePrompt;
import com.witmore.skyline.web.service.third.neutronAI.dto.NeutronResult;
import com.witmore.skyline.web.utils.LocalDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * Description: ApiClient 第三方接口调用
 * Author: 豆子高
 * Date: 2025/2/24 14:26
 */
@Slf4j
@Component
public class NeutronAIApiChatClient {

    @Autowired
    private NeutronAIApiClient neutronAIApiClient;

    public NeutronResult neutronChatCompletions(String cameraSn, String ossUrl) throws Exception {
        try {
            ApiChatCompletionRequest apiChatCompletionRequest = new ApiChatCompletionRequest();
            apiChatCompletionRequest.setStream(false);
            apiChatCompletionRequest.setResponseType("json");
            apiChatCompletionRequest.setSysPromptOverride(false);
            apiChatCompletionRequest.setSessionId("api-witmore-" + cameraSn + "-" + LocalDateUtils.dateConvertString(LocalDate.now(), "yyyyMMdd"));
            ApiMessagePrompt.Content content = new ApiMessagePrompt.Content();
            content.setType("image_url");
            content.setUrl(ossUrl);
            apiChatCompletionRequest.getMessages().add(new ApiMessagePrompt("user", JSONArray.toJSONString(List.of(content))));
            ResponseResult<String> stringResponseResult = neutronAIApiClient.neutronChatCompletions(apiChatCompletionRequest);
            if (stringResponseResult == null || stringResponseResult.getCode() != 200) {
                log.error("NeutronAIApiChatClient error: {}", stringResponseResult != null ? stringResponseResult.getMessage() : "未知错误");
                throw new RuntimeException("AI接口调用失败，错误信息: " + (stringResponseResult != null ? stringResponseResult.getMessage() : "未知错误"));
            }
            String response = stringResponseResult.getData();
            // 过滤出Markdown格式的 ```json  ```
            if (StringUtils.isEmpty(response)) {
                throw new Exception("NeutronAIApiClient response is empty");
            }
            if (response.startsWith("```json") && response.endsWith("```")) {
                // 去除开头的 ```json 和结尾的 ```
                response = response.substring(8, response.length() - 3).trim();
            }
            return JSONObject.parseObject(response, NeutronResult.class);
        } catch (Exception e) {
            log.error("NeutronAIApiChatClient error: {}", e.getMessage());
            throw new Exception(e.getMessage(), e);
        }
    }

}
